{-# LANGUAGE DeriveGeneric, FlexibleInstances, RecordWildCards #-}

module App.Common.Table (PageInfo(..),Table(..),isPrv,isNext,maxPage) where
import GHC.Generics
import Data.Aeson
import qualified Data.List as L
data Table a = Table {
    total::Int,
    pageInfo::PageInfo,
    tableData::[a]
} deriving(Eq,Show,Generic)

instance Functor Table where
  fmap f tb@Table{..} = tb {tableData = L.map f tableData }

data PageInfo = PageInfo {
  curPage     ::Int,
  pageSize    ::Int
} deriving(Eq,Show,Generic)

instance ToJSON PageInfo
instance (ToJSON a) => ToJSON (Table a)

isPrv::Table a -> Bool
isPrv tab = (curPage.pageInfo $ tab) > 0

-- 0 15 - 10 = 5
--   15 - 10 = 5

isNext::Table a -> Bool
isNext tab =  ((total tab) - cpmps) > 0
  where
    pInfo = pageInfo tab
    cp    = curPage pInfo
    ps    = pageSize pInfo
    cpmps = (cp+1) * ps

maxPage::Table a -> Int
maxPage tab =  if isMdZero then divTP else divTP + 1
 where
  t  = total tab
  ps = pageSize $ pageInfo tab
  isMdZero = (t `mod` ps) == 0
  divTP    = t `div` ps